import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'dart:async';
import '../../config/app_colors.dart';
import '../../config/app_url_address.dart';
import '../../model/productHotListModel.dart';
import '../../utils/JoyCacheManager.dart';
import '../../utils/route_utils.dart';
import '../../utils/CountdownManager.dart';
import '../../utils/currency_manager.dart';
import '../joy_product_detail_page.dart';

class JoyProductHotCardWidget extends StatefulWidget {
  final ProductHotModel? productModel;
  final VoidCallback? onTap;
  final VoidCallback? onFavorite;

  const JoyProductHotCardWidget({
    super.key,
    this.productModel,
    this.onTap,
    this.onFavorite,
  });

  @override
  State<JoyProductHotCardWidget> createState() => _JoyProductHotCardWidgetState();
}

class _JoyProductHotCardWidgetState extends State<JoyProductHotCardWidget> {
  final CountdownManager _countdownManager = CountdownManager();
  CountdownData? _countdownData;
  bool _isActive = false;

  @override
  void initState() {
    super.initState();
    _initializeCountdown();
    _countdownManager.addListener(_onCountdownUpdate);
  }

  @override
  void dispose() {
    _countdownManager.removeListener(_onCountdownUpdate);
    super.dispose();
  }

  @override
  void didUpdateWidget(JoyProductHotCardWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.productModel?.id != widget.productModel?.id) {
      _initializeCountdown();
    }
  }

  void _initializeCountdown() {
    final product = widget.productModel;
    if (product == null) return;
    
    // 检查是否有活动 (status == "1")
    _isActive = product.status == "1";
    
    if (_isActive && product.currentTime != null && product.endTime != null) {
      // 将倒计时数据添加到全局管理器
      _countdownManager.addCountdown(product.id, product.currentTime!, product.endTime!);
      _countdownData = _countdownManager.getCountdown(product.id);
      
      // 启动全局倒计时（如果还没启动）
      _countdownManager.startGlobalCountdown();
    } else {
      _countdownData = null;
    }
  }

  void _onCountdownUpdate() {
    if (mounted) {
      final product = widget.productModel;
      if (product != null) {
        _countdownData = _countdownManager.getCountdown(product.id);
        setState(() {
          // 更新状态
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        JoyNavUtils().to(JoyProductDetailPage(itemNo: widget.productModel?.channelItemNo??"",channel: widget.productModel?.channel??"",productName: widget.productModel?.title??"",));

      },
      child: Card(
        margin: EdgeInsets.zero,
        elevation: 8,
        shadowColor: Colors.black.withOpacity(0.15),
        color: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12.r),
        ),
        clipBehavior: Clip.antiAlias,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 倒计时横幅
            if (_isActive && _countdownData != null && _countdownData!.isActive)
              _buildCountdownBanner(),
            // 商品图片
            Expanded(
              child: Stack(
                children: [
                  Column(
                    children: [
                      Expanded(
                        child: Container(
                          child: CachedNetworkImage(
                              cacheManager: JoyCacheManager.instance,
                              imageUrl:  showPictureUrl(widget.productModel?.mainImageChannel??""),
                              width: double.infinity,
                              fit: BoxFit.cover,
                              placeholder: (context, url) => Container(
                                color: AppColors.backgroundSecondary,
                                child: Center(
                                  child: CircularProgressIndicator(
                                    strokeWidth: 2,
                                    valueColor: AlwaysStoppedAnimation<Color>(
                                      AppColors.textHint,
                                    ),
                                  ),
                                ),
                              ),
                              errorWidget: (context, url, error) => Container(
                                color: AppColors.backgroundSecondary,
                                child: Icon(
                                  Icons.image_not_supported,
                                  size: 32.sp,
                                  color: AppColors.textHint,
                                ),
                              ),
                            ),
                        ),
                      )
                    ],
                  ),
                  // 折扣标签
                  // if (_isActive && widget.productModel?.discountRate != null && widget.productModel!.discountRate! > 0)
                  //   Positioned(
                  //     top: 8.h,
                  //     right: 8.w,
                  //     child: Container(
                  //       padding: EdgeInsets.symmetric(
                  //         horizontal: 8.w,
                  //         vertical: 4.h,
                  //       ),
                  //       decoration: BoxDecoration(
                  //         color: Color(0xFFFF6B35),
                  //         borderRadius: BorderRadius.circular(8.r),
                  //         boxShadow: [
                  //           BoxShadow(
                  //             color: Color(0xFFFF6B35).withOpacity(0.3),
                  //             blurRadius: 4,
                  //             offset: Offset(0, 2),
                  //           ),
                  //         ],
                  //       ),
                  //       child: Text(
                  //         '${(widget.productModel!.discountRate! * 100).round()}% OFF',
                  //         style: TextStyle(
                  //           color: Colors.white,
                  //           fontSize: 12.sp,
                  //           fontWeight: FontWeight.bold,
                  //         ),
                  //       ),
                  //     ),
                  //   ),
                  // 新品标签
                  if (isNewProduct())
                    Positioned(
                      bottom: 8.h,
                      left: 8.w,
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 8.w,
                          vertical: 4.h,
                        ),
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            colors: [
                              Color(0xFF00C9FF),
                              Color(0xFF92FE9D),
                            ],
                            begin: Alignment.topLeft,
                            end: Alignment.bottomRight,
                          ),
                          borderRadius: BorderRadius.circular(12.r),
                          boxShadow: [
                            BoxShadow(
                              color: Color(0xFF00C9FF).withOpacity(0.3),
                              blurRadius: 4,
                              offset: Offset(0, 2),
                            ),
                          ],
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(
                              Icons.fiber_new,
                              size: 12.sp,
                              color: Colors.white,
                            ),
                            SizedBox(width: 2.w),
                            Text(
                              '新品',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 10.sp,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                ],
              ),
            ),
            // 商品信息
            Padding(
              padding: EdgeInsets.all(6.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    widget.productModel?.title??"",
                    style: TextStyle(
                      fontSize: 13.sp,
                      fontWeight: FontWeight.w500,
                      color: AppColors.textHint,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  SizedBox(height: 2.h),
                  _buildPriceSection(),
                  SizedBox(height: 2.h),
                  showdiscountRate()

                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
  // 构建价格显示区域
  Widget _buildPriceSection() {
    final product = widget.productModel;
    if (product == null) {
      return Text(
        "${CurrencyManager.instance.currentCurrency.symbol}0.00",
        style: TextStyle(
          fontSize: 14.sp,
          fontWeight: FontWeight.bold,
          color: AppColors.textPrimary,
        ),
      );
    }

    String displayPrice = "";
    String originalPrice = "";
    bool showDiscount = false;

    if (_isActive && product.status == "1" && _countdownData != null && _countdownData!.isActive) {
      // 活动期间：显示折扣价，原价作为对比
      displayPrice = product.price.toStringAsFixed(2);
      if (product.discountPrice != null && product.discountPrice! > 0) {
        originalPrice = product.discountPrice!.toStringAsFixed(2);
      }
      showDiscount = true;
    } else {
      // 非活动期间：优先显示原价，如果原价为null或0则显示折扣价
      if (product.discountPrice != null && product.discountPrice! > 0) {
        displayPrice = product.discountPrice!.toStringAsFixed(2);
        originalPrice = "";
      } else {
        displayPrice = product.price.toStringAsFixed(2);
        originalPrice = "";
      }
      showDiscount = false;
    }

    return Row(
      children: [
        Text(
          "${CurrencyManager.instance.currentCurrency.symbol}${displayPrice}",
          style: TextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.bold,
            color: AppColors.textPrimary,
          ),
        ),
        if (originalPrice.isNotEmpty) ...[
          // SizedBox(width: 8.w),
          Text(
            "/${CurrencyManager.instance.currentCurrency.symbol}${originalPrice}",
            style: TextStyle(
              fontSize: 12.sp,
              color: AppColors.textHint,
              decoration: TextDecoration.lineThrough,
            ),
          ),
        ],
        // if (showDiscount && product.discountRate != null && product.discountRate! > 0) ...[
        //   SizedBox(width: 8.w),
        //   Container(
        //     padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 2.h),
        //     decoration: BoxDecoration(
        //       color: Color(0xFFFF6B35),
        //       borderRadius: BorderRadius.circular(4.r),
        //     ),
        //     child: Text(
        //       "${(product.discountRate! * 100).round()}% OFF",
        //       style: TextStyle(
        //         color: Colors.white,
        //         fontSize: 10.sp,
        //         fontWeight: FontWeight.bold,
        //       ),
        //     ),
        //   ),
        // ],
      ],
    );
  }

  Widget showdiscountRate(){
    final product = widget.productModel;
    if (product == null) return Container();
    
    double discountRates = product.discountRate ?? 0.0;
    
    // 根据活动状态判断是否显示折扣标签
    bool shouldShowDiscount = false;
    
    if (_isActive && product.status == "1" && _countdownData != null && _countdownData!.isActive) {
      // 活动期间：显示折扣标签
      shouldShowDiscount = discountRates > 0;
    } else {
      // 非活动期间：不显示折扣标签
      shouldShowDiscount = false;
    }
    
    if (!shouldShowDiscount || discountRates == 0) {
      return Container();
    }

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 4.w, vertical: 2.h),
      decoration: BoxDecoration(
        color: AppColors.backHomeYellowGround, // 浅橙色背景
        borderRadius: BorderRadius.circular(6.r),
        border: Border.all(
          color: AppColors.backHomeYellowGround, // 深橙色边框
          width: 1.0,
        ),
      ),
      child: Text(
        "${(discountRates * 100).round()}% OFF",
        style: TextStyle(
          color: AppColors.primaryVariant, // 深橙色文字
          fontSize: 12.sp,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  // 构建倒计时横幅
  Widget _buildCountdownBanner() {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.all(0.w),
      padding: EdgeInsets.symmetric(horizontal: 0.w, vertical: 4.h),
      decoration: BoxDecoration(
        color: AppColors.primaryVariant,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(12.r),
          topRight: Radius.circular(12.r)
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            'Time Left: ',
            style: TextStyle(
              color: Colors.white,
              fontSize: 12.sp,
              fontWeight: FontWeight.w500,
            ),
          ),
          Text(
            _countdownData?.formattedTime ?? '00H:00M:00S',
            style: TextStyle(
              color: AppColors.backHomeYellowGround,
              fontSize: 13.sp,
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }

  // 判断是否为新品（10天内创建的商品）
  bool isNewProduct() {
    return false;
    final createAt = widget.productModel?.createAt;
    if (createAt == null || createAt.isEmpty) {
      return false;
    }

    try {
      final createTime = DateTime.parse(createAt);
      final daysDifference = DateTime.now().difference(createTime).inDays;
      return daysDifference <= 10;
    } on FormatException catch (e) {
      debugPrint('日期格式错误: $createAt, 错误: $e');
      return false;
    } catch (e) {
      debugPrint('解析创建时间失败: $createAt, 错误: $e');
      return false;
    }
  }

  String showPictureUrl(String url){

    String main = "";
    if(url.contains("http")){
      main =  url;
    }else{
      main = "${joyProductPicUrl}${url}";
    }

    String mainUrl = Uri.encodeFull(main);
    return mainUrl;
  }
}